package logic.nodes.damagable;

import java.util.Random;

import sound.AudioManager;

import factories.EffectFactory;
import fileHandling.ModelImporter;
import fileHandling.TextureLoader;
import input.StraightForwardBinding;
import logic.nodes.MoveForwardController;

import com.jme.input.controls.GameControl;
import com.jme.math.Vector3f;
import com.jme.scene.Controller;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;

public class DestroyController extends Controller {
	
	private static final long serialVersionUID = 1L;
	
	private final float MAX_TIME = 1.2f;
	private final float EXPLOSION_TIME = 0.8f;
	
	private Random r;	
	private GameControl forward, backward;
	private float currentTime;
	private Node model;
	private int explosionsLeft;
	private String destructionSound;
	
	public DestroyController(DamagableNode node) {
		model = ModelImporter.getModelOfQuality(node.getPath(), "lod1");
		if(model == null) return;
		
		destructionSound = node.getDestructionSound();
		
		model.getLocalTranslation().set(node.getLocalTranslation());
		model.setLocalScale(node.getDefaultScale());
		model.getLocalRotation().set(node.getLocalRotation());
		node.getParent().attachChild(model);
		
		r = new Random();

		forward = StraightForwardBinding.getGameControl(StraightForwardBinding.forward);
		backward = StraightForwardBinding.getGameControl(StraightForwardBinding.backward);
		
		manageTriMeshes(model);
		
		explosionsLeft = 2;
	}
	
	private void manageTriMeshes(Node parent) {
		for(Spatial child : parent.getChildren()) {
			if(child instanceof Node) manageTriMeshes((Node)child);
			else {
				TriMesh mesh = (TriMesh)child;
				TextureLoader.updateTextureQuality(mesh, "lod3");
				mesh.addController(getController(mesh));
			}
		}
	}
	
	private MoveForwardController getController(Spatial child) {
		final Vector3f dir = new Vector3f(nextParam(), nextParam(), nextParam()).normalizeLocal();
		return new MoveForwardController(child, forward, 0.5f, 0f, 1.8f, backward, 0f) {
			private static final long serialVersionUID = 1L;
			@Override
			protected void move(float tpf) { node.getLocalTranslation().addLocal(dir.mult(currentSpeed)); }
		};
	}
	
	private float nextParam() {
		float param = r.nextFloat();
		return (r.nextBoolean() ? param : -param);
	}
	
	public Node getModel() { return model; }
	
	@Override
	public void update(float time) {
		currentTime += time;
		if(currentTime >= MAX_TIME) {
			model.removeFromParent();
			model = null;
		} else if(currentTime >= EXPLOSION_TIME && explosionsLeft > 0) {
			EffectFactory.createSecondaryNodeExplosion(model);
			AudioManager.get().playSound(destructionSound, model.getLocalTranslation());
			explosionsLeft--;
		}
	}
}